<template>
	<h3>WhyRef</h3>
	<p>x:{{ x }} y:{{ y }}</p>
	<hr />
	<p>name:{{ state.name }}</p>
	<p>age:{{ state.age }}</p>
	<hr />
	<p>name:{{ name }}</p>
	<p>age1:{{ age }}</p>
	<hr />
	<button @click="sayHello">hello</button>
	<button @click="sayHello()">hello</button>
	<hr />
	<div ref="divRef">你妹</div>
	<button @click="changeText">change text</button>
	<hr />
	实岁{{ age }} <br />
	虚岁{{ xusui }}
</template>

<script setup>
	/* 最外层的一切（变量、方法、模块...）都直接对模板暴露 */
	import {
		ref,
		toRef,
		toRefs,
		reactive,
		computed,
		onMounted,
		onUnmounted,
	} from "vue";

	function useMousePosition() {
		const state = reactive({
			x: 1,
			y: 2,
		});

		const updateMousePosition = (e)=>{
			state.x = e.pageX
			state.y = e.pageY
		}

		onMounted(
			()=>window.addEventListener("mousemove",updateMousePosition)
		)

		onUnmounted(
			()=>window.removeEventListener("mousemove",updateMousePosition)
		)

		// return 响应式数据 {x,y}
		return toRefs(state);
	}

	/* 自定义hook */
	const { x, y } = useMousePosition();

	/* 通过ref抓取DOM元素 */
	// divRef.value
	const divRef = ref(null);

	/* option-Api/vue2中data的替换者 */
	// 打散对组件暴露出name,age=>   return toRefs(state)
	const state = reactive({
		age: 20,
		name: "steve",
	});

	const {name,age} = toRefs(state)

	// computed
	// 由年龄计算虚岁
	const xusui = computed(() => {
		return state.age + 1;
	});

	/* 对模板暴露函数 */
	const sayHello = () => {
		alert("hello");
	};
	function changeText() {
		divRef.value.innerText = "令妹";
	}

	/* 声明周期 */
	let timer = null;
	onMounted(() => {
		timer = setInterval(() => {
			state.age += 1;
		}, 1000);
	});
	
	onUnmounted(() => {
		clearInterval(timer);
		console.log("定时器已被移除");
	});
</script>